<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="format-detection" content="telephone=no" />
    <meta name="format-detection" content="email=no" />
    <title>店铺</title>
    <link rel="stylesheet" href="../../css/api.css">
    <link rel="stylesheet" href="../../css/vant.css">
    <link rel="stylesheet" href="../../css/main.css">
    <style>
        .toAddress{
            background-color: #fff;
            margin: .04rem 0;
            padding: .2rem 0.12rem;
            font-size: .12rem;
        }
        .cart-detail-order-info .info{
            width: 1.8rem;
        }
        .cart-detail-order-add{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .cart-detail-order-add .opt-item{
            width: 0.33rem;
            height: 0.2rem;
            border: 0.01rem solid #ccc;
            border-width: 0.01rem 0 0.01rem 0.01rem;
        }
        .cart-detail-order-add .opt-item:last-child {
            border-right: .01rem solid #ccc;
        }
        .cart-detail-order-add .sub {
            background: url('https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/cart/sub-icon.png') no-repeat;
            background-position: 50% 50%;
            background-size: 40% auto;
        }

        .cart-detail-order-add .add {
            background: url('https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/cart/add-icon.png') no-repeat;
            background-position: 50% 50%;
            background-size: 40% auto;
        }

        .cart-detail-order-add .cart-total {
            text-align: center;
            line-height: 0.2rem;
            color: #3F8CEC;
        }
    </style>
</head>

<body>
    <div class="app" v-cloak>
        <div class="iphonex-padding-bottom">
            <div @click="forwardPage('address_list_win', '../address/',{status:'select'})">
                <div class="cart-detail-area" v-if="buildOrderDetail.userAddress">
                    <div class="top" >
                        <div >
                            <div class="title">
                                <span>{{buildOrderDetail.userAddress.name}}</span>
                                <span>{{buildOrderDetail.userAddress.phone}}</span>
                            </div>
                            <div>{{buildOrderDetail.userAddress.provinceName | filtersProvince}}{{buildOrderDetail.userAddress.cityName}}{{buildOrderDetail.userAddress.areaName}} {{buildOrderDetail.userAddress.address}}</div>
                        </div>
                        <span class="iconfont">&#xe666;</span>
                    </div>
                </div>
                <div class="flex-x-sb toAddress" v-else>
                    <div>请选择收货地址</div>
                    <div class="iconfont">&#xe666;</div>
                </div>
            </div>

            <div class="cart-detail-order-list">
                <div class="cart-detail-order-item" v-for="(shop,index) in buildOrderDetail.shops" :key="index">
                    <div>{{shop.shopName}}</div>
                    <div v-for="(product,idx) in shop.products" :key="idx">
                        <div class="cart-detail-order-info">
                            <div class="img">
                                <img :src="product.imageUrl?product.imageUrl:'https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/default/item_img.png'" alt="">
                            </div>
                            <div class="info">
                                <div>{{product.name}}</div>
                                <div class="money"><span>¥</span>{{Number(product.price).toFixed(2)}}</div>
                            </div>
                            <div class="cart-detail-order-add">
                                <div class="opt-item sub" @click="changeQuality(shop, product,-1)"></div>
                                <div class="cart-total opt-item">{{product.quantity}}</div>
                                <div class="opt-item add" @click="changeQuality(shop, product,1)"></div>
                            </div>
                        </div>
                        <div class="cart-detail-order-discount flex-x-sb" v-if="product.productPromotion">
                            <div class="cart-detail-order-discount-info">
                                <span>商品优惠</span>
                                <span>倒计时：{{product.productPromotion.countDown}}</span>
                            </div>
                            <div>- ¥ {{Number(product.productPromotion.reducePrice).toFixed(2)}}</div>
                        </div>
                    </div>
                    <div class="cart-detail-order-discount flex-x-sb" v-if="shop.shopPromotion">
                        <div class="cart-detail-order-discount-info">
                            <span>店铺优惠</span>
                            <span>倒计时：{{shop.shopPromotion.countDown}}</span>
                        </div>
                        <div>- ¥ {{shop.shopPromotion.reducePrice}}</div>
                    </div>
                    <div class="cart-detail-order-total">
                        总计：¥ {{shop.resultAmount}}
                    </div>
                </div>
            </div>
            <div class="cart-create-order" v-if="buildOrderDetail.platformPromotion">
                <div class="cart-create-order-txt flex-x-sb">
                    <span>平台优惠</span>
                    <span>- ¥ {{Number(buildOrderDetail.platformPromotion.reducePrice).toFixed(2)}}</span>
                </div>
                <div>倒计时：{{buildOrderDetail.platformPromotion.countDown}}</div>
            </div>
        </div>
        <div class="cart-detail-order-submit flex-x-sb">
            <div class="money">
                <span>合计：</span>
                <span>¥</span>
                <span>{{Number(buildOrderDetail.resultAmount).toFixed(2)}}</span>
            </div>
            <div class="btn" @click="sumbit">提交订单</div>
        </div>
        <van-popup v-model="show" closeable round position="bottom" :style="{ height: '40%' }">
            <div class="pay-method">
                <div class="money"><span>¥</span>{{Number(buildOrderDetail.resultAmount).toFixed(2)}}</div>
                <div>付款方式</div>
                <div class="wx-pay flex-x-sb" @click="selectPayMethod(1)">
                    <div class="flex-x-s">
                        <img src="https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/cart/wxpay.png" alt="">
                        <span>微信支付</span>
                    </div>
                    <img class="selectImg" :src="queryParam.payMethod===0?'https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/cart/select.png':'https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/cart/no-select.png'" alt="">
                </div>
                <div class="wx-pay flex-x-sb" @click="selectPayMethod(2)">
                    <div class="flex-x-s">
                        <img src="https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/cart/zfbpay.png" alt="">
                        <span>支付宝</span>
                    </div>
                    <img class="selectImg" :src="queryParam.payMethod===3?'https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/cart/select.png':'https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/cart/no-select.png'" alt="">
                </div>
                <div class="pay" @click="pay">立即支付</div>
            </div>
        </van-popup>
    </div>
    <script src="../../script/api.js"></script>
    <script src="../../script/flexible.js"></script>
    <script src="../../script/vue.min.js"></script>
    <script src="../../script/iconfont.js"></script>
    <script src="../../script/fastclick.js"></script>
    <script src="../../script/vant.min.js"></script>
    <script src="../../script/common.js"></script>
    <script src="../../script/restful.js"></script>
    <script src="../../script/businessCommon.js"></script>

    <script>
        apiready = function() {
            vm = new Vue({
                el: '.app',
                data: {
                    show: false,
                    buildOrderDetail:{
                        userAddress:{},
                        shops:[],
                        resultAmount: ''
                    },
                    queryParam:{
                        payMethod:0,
                        receiverId:null,
                        shops:[]
                    },
                    checkOrderStatusTimer:null,
                    checkStatus:false,
                    shops: api.pageParam.shops
                },
                filters:{
                    //过滤掉直辖市
                    filtersProvince(val){
                        if (val== ("上海市" || "天津市" || "重庆市" || "北京市")) {
                            return ""
                        } else {
                            return val
                        }
                    }
                },
                created() {
                },
                mounted() {
                    this.buildOrder()
                },
                methods: {
                    submitOrder() {

                    },

                    // 数量更改
                    changeQuality: function (shop, product, quantity) {
                        let change = false
                        let tempShop = this.shops
                        for (let i = 0; i < this.shops.length; i++) {
                            let currentShop = this.shops[i]
                            if (currentShop.shopId == shop.shopId) {
                                let shopProducts = currentShop.products
                                for (let j = 0; j < shopProducts.length; j++) {
                                    let currentProduct = shopProducts[j]
                                    if (currentProduct.id == product.id) {
                                        if (tempShop[i].products[j].quantity == 1 && quantity < 0) {
                                            // toastMiddle('不能再少了！')
                                            break
                                        } else {
                                            tempShop[i].products[j].quantity += quantity
                                            change = true
                                        }
                                    }
                                }
                            }
                        }
                        if (change) {
                            this.shops = tempShop
                            this.buildOrder()
                        }
                    },

                    sumbit() {
                        this.show = true
                    },
                    forwardPage(url, relative,pageParam) {
                        api.openWin({
                            name: url,
                            url: (relative || "") + url + ".html",
                            pageParam:pageParam || {}
                        })
                    },
                    //付款成功后的状态
                    paySuccess:function(){
                        toastMiddle('支付成功')
                        api.sendEvent({
                            name: 'paySuccess',
                        });
                        setTimeout(function () {
                            vm.toOrderPage();
                        }, 500)
                        api.sendEvent({name: 'closeWin', extra: {name: 'create_order_win', delay: 2000}});
                    },
                    payFail:function(){
                        toastMiddle('支付失败')
                        api.sendEvent({
                            name: 'payFail',
                        });
                        setTimeout(function () {
                            vm.toOrderPage();
                        }, 500)
                        api.sendEvent({name: 'closeWin', extra: {name: 'create_order_win', delay: 2000}});
                    },
                    toOrderPage() {
                        api.openWin({
                            name: 'my_order_win',
                            url: '../my_order/my_order_win.html',
                            // bounces: false,
                        });
                    },
                    //微信支付
                    wxPay:function(data){
                        var vm = this;
                        var wxPayPlus = api.require('wxPayPlus');
                        wxPayPlus.payOrder({
                            apiKey: data.appId,
                            orderId: data.prepayId,
                            mchId: data.partnerId,
                            nonceStr: data.nonceStr,
                            timeStamp: data.timeStamp,
                            package: data.packageValue,
                            sign: data.sign
                        }, function(ret, err) {
                            if (ret.status) {
                                vm.paySuccess()
                            } else {
                                vm.payFail()
                            }
                        });
                    },
                    //支付宝支付
                    aliPay:function(data){
                        var vm = this
                        var aliPayPlus = api.require('aliPayPlus');
                        aliPayPlus.payOrder({
                            orderInfo: data
                        }, function(ret, err) {
                            if(ret.code==9000){
                                vm.paySuccess()
                            }else{
                                vm.payFail()
                            }
                        });
                    },
                    // 检查支付状态
                    checkOrderStatus(sn){
                        var vm = this;
                        order('checkOrderStatus')(sn,function(ret){
                            if(ret.data.status === 'WAIT_PAY'){
                                // 成功
                                clearInterval(vm.checkOrderStatusTimer)
                                api.hideProgress();
                                vm.show = false;
                                // 创建订单成功 调微信和支付宝
                                if(!vm.checkStatus){
                                    vm.checkStatus = true
                                    if(vm.queryParam.payMethod == 0){
                                        // 微信
                                        vm.wxPay(ret.data.wxPayAppOrderResult)
                                    }else if (vm.queryParam.payMethod == 3){
                                        // 支付宝
                                        vm.aliPay(ret.data.aliPayBody)
                                    }
                                }
                            }else if (ret.data.status === 'PRE_PAY_FAIL'){
                                // 失败
                                clearInterval(vm.checkOrderStatusTimer)
                                api.hideProgress();
                                vm.show = false;
                                toastMiddle('创建订单失败')
                            }
                        })
                    },
                    // 立即支付
                    pay(){
                        console.log(JSON.stringify(this.buildOrderDetail));
                        if(this.queryParam.payMethod === null){
                            toastMiddle('请选择付款方式')
                            return
                        }
                        if( !this.buildOrderDetail.userAddress || this.buildOrderDetail.userAddress === null){
                            toastMiddle('请选择地址')
                            return
                        }
                        this.queryParam.shops = this.shops
                        this.queryParam.receiverId = this.buildOrderDetail.userAddress.id
                        var vm = this;
                        api.showProgress({title: '小蟹加载中...', text: '', modal: true});
                        order('createOrder')(this.queryParam,function(ret){
                            vm.checkStatus = false
                            vm.checkOrderStatusTimer = setInterval(()=>{
                                vm.checkOrderStatus(ret.data.paymentSn)
                            },500)
                        })
                    },
                    // 选择支付方式
                    selectPayMethod(type){
                        if(type == 1){
                            this.queryParam.payMethod = 0
                        }else{
                            this.queryParam.payMethod = 3
                        }
                    },
                    // 构建订单
                    buildOrder(){
                        var vm = this;
                        var shops = vm.shops
                        var param = {
                            shops:shops
                        }
                        console.log("构建订单param："+JSON.stringify(vm.shops))
                        console.log("构建订单param："+JSON.stringify(param))
                        order('buildOrder')(param,function(ret){
                            console.log("构建订单："+JSON.stringify(ret.data))
                            vm.buildOrderDetail = ret.data
                            // 设置优惠倒计时
                            if(vm.buildOrderDetail.platformPromotion){
                                var now = new Date().getTime()
                                vm.$set(vm.buildOrderDetail.platformPromotion,'countDown',vm.formatHms(vm.buildOrderDetail.platformPromotion.endTime, now))
                                setInterval(()=>{
                                    var now = new Date().getTime()
                                    vm.$set(vm.buildOrderDetail.platformPromotion,'countDown',vm.formatHms(vm.buildOrderDetail.platformPromotion.endTime, now))
                                },1000)
                            }
                            vm.buildOrderDetail.shops.map(shop=>{
                                if(shop.shopPromotion){
                                    var now = new Date().getTime()
                                    vm.$set(shop.shopPromotion,'countDown',vm.formatHms(shop.shopPromotion.endTime, now))
                                    setInterval(()=>{
                                        var now = new Date().getTime()
                                        vm.$set(shop.shopPromotion,'countDown',vm.formatHms(shop.shopPromotion.endTime, now))
                                    },1000)
                                }
                                shop.products.map(product=>{
                                    if(product.productPromotion){
                                        var now = new Date().getTime()
                                        vm.$set(product.productPromotion,'countDown',vm.formatHms(product.productPromotion.endTime, now))
                                        setInterval(()=>{
                                            var now = new Date().getTime()
                                            vm.$set(product.productPromotion,'countDown',vm.formatHms(product.productPromotion.endTime, now))
                                        },1000)
                                    }
                                })

                            })
                        })
                    },
                    // 倒计时处理
                    formatHms(endDateTime, startDateTime) {
                        var seconds = (parseInt(endDateTime - startDateTime) / 1000);
                        var h = Math.floor(seconds / (60 * 60));
                        var m = Math.floor(seconds % (60 * 60) / 60);
                        var s = Math.floor(seconds % (60 * 60) % 60);
                        return (h < 10 ? ('0' + h) : h) + ' 时 ' + (m < 10 ? ('0' + m) : m) + ' 分 ' + (s < 10 ? ('0' + s) : s) + ' 秒';
                    },
                },
            })
            api.addEventListener({
                name: 'orderType'
            }, function(ret, err) {
                var active = ret.value.active
            });
            api.addEventListener({
                name: 'eventSelectAddress'
            }, function(ret, err) {
                // vm.buildOrderDetail.receiver = ret.value.item
                vm.$set(vm.buildOrderDetail,'userAddress', ret.value.item)
            });
        }
    </script>
</body>

</html>
